// base
import Taro, { Component } from '@tarojs/taro'
import { View, Button, Input, Image, Text } from '@tarojs/components'
// redux
import { connect } from '@tarojs/redux'
import { UPDATEPAGEPHONEVALIDATION } from './store/types/pagephonevalidation'
// less
import './index.less'

import { queryUserId, changeMobile } from '../../store/actions/userinfo'
import { checkPhoneMark, phoneBg } from '../../configuration/staticimg'
import { showToast } from '../../crossplatform/apiservice/toast'
import { sendCodeRequest } from '../../service/auth-code-controller'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'

const mapActiontoProps = dispatch => ({
  updateState (payload) {
    dispatch({
      type: UPDATEPAGEPHONEVALIDATION,
      payload: {
        ...payload
      }
    })
  },
  loginRequest (payload) {
    dispatch(queryUserId({ ...payload }))
  },
  ChangeMobileC ({ ...payload }) {
    dispatch(changeMobile({ ...payload }))
  },
  ChangeMobileB (payload) {
    dispatch(changeMobile({ ...payload }))
  }
})

@connect(
  ({ pagephonevalidation, userinfo }) => ({
    ...pagephonevalidation,
    openId: userinfo.openId,
    userId: userinfo.userId,
    userInfoC: userinfo.userInfoC,
    userInfoB: userinfo.userInfoB
  }),
  mapActiontoProps
)
class PhoneValidation extends Component {
  config = {
    navigationBarTitleText: ''
  }

  constructor (props) {
    super(props)
    this.state = {
      cant: true,
      isSendCode: false,
      text: '获取验证码',
      textOpacity: true,
      isLogin: false,
      agreeChecked: false
    }
  }

  componentWillMount () {
    // onLoad
    const { login = '' } = this.$router && this.$router.params
    this.setState({
      isLogin: login
    })
  }

  componentDidMount () {
    // onready
  }

  componentDidShow () {
    // onshow
  }

  componentDidHide () {
    // onhide
  }

  componentWillUnmount () {
    // onUnload
    this.props.updateState({
      phone: '',
      validation: ''
    })
    this.setState({
      cant: true,
      isSendCode: false,
      text: '获取验证码',
      textOpacity: true,
      agreeChecked: false
    })
  }

  delay (time = 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  onTap = () => {
    const { type, detailIn, roleType } = this.$router && this.$router.params
    const { phone, validation, openId, userId } = this.props
    const { agreeChecked, isLogin } = this.state
    if ((!isLogin || agreeChecked) && phone && validation) {
      if (type == 'changemobilec') {
        this.props.ChangeMobileC({
          mobile: phone,
          code: validation,
          type: 'userId',
          identifier: userId + ''
        })
      } else if (type == 'changemobileb') {
        this.props.ChangeMobileB({
          mobile: phone,
          code: validation,
          type: 'userId',
          identifier: userId + ''
        })
      } else {
        this.props.loginRequest({
          mobile: phone,
          code: validation,
          type: 'openId',
          identifier: openId,
          isLogin: true,
          detailIn,
          roleType
        })
      }
    } else {
      if (!(!isLogin || agreeChecked)) {
        showToast({
          title: '请阅读并同意人职初条款'
        })
        return
      }
      if (!phone) {
        showToast({
          title: '请填写手机号'
        })
        return
      }
      if (!validation) {
        showToast({
          title: '请填写验证码'
        })
      }
    }
  }

  onMobileInput = event => {
    const { value } = event.detail
    this.props.updateState({
      phone: value
    })
    if (value.length == 11) {
      this.setState({
        cant: false
      })
    }
  }

  onPhoneInput = event => {
    let validation = event.detail.value
    this.props.updateState({
      validation
    })
  }

  hideInput = () => {
    this.props.updateState({ showInput: false })
  }

  sendMessage = () => {
    const { cant } = this.state
    if (!cant) {
      const { phone } = this.props
      if (/^\d{11}$/.test(phone)) {
        this.sendCapcth({ mobile: phone })
      } else {
        showToast({
          title: '手机号码不正确！'
        })
      }
    }
  }

  sendCapcth = ({ mobile }) => {
    const { text } = this.state
    this.setTime()
    if (!/\d/.test(text)) {
      sendCodeRequest({ mobile }).then(({ data: { message, code, data: dataCode } = {} }) => {
        if (code === 200) {
          showToast({
            title: (dataCode && dataCode.vcode) || '已发送'
          })
          this.setState({
            isSendCode: true
          })
        } else {
          showToast({
            title: message || '发送失败'
          })
        }
      })
    }
  }

  setTime = () => {
    let text = 60
    this.setState({
      text: `已发送(${text}s)`,
      textOpacity: true,
      cant: true
    })
    clearInterval(this.timer)
    this.timer = setInterval(() => {
      text -= 1
      this.setState({
        text: `已发送(${text}s)`,
        textOpacity: true
      })
      if (text <= 0) {
        clearInterval(this.timer)
        this.setState({
          text: '重新发送',
          textOpacity: false,
          cant: false
        })
      }
    }, 1000)
  }

  ruleChecked = () => {
    const { agreeChecked } = this.state
    this.setState({
      agreeChecked: !agreeChecked
    })
  }

  goRules = () => {
    // 跳转到人职初协议页面
    navigateTo({
      url: `${pagejumplist['agreement-page'].path}`
    })
  }

  render () {
    const { validation, phone } = this.props
    const { cant, isSendCode, text, textOpacity, isLogin, agreeChecked } = this.state
    return (
      <View className="PhoneValidation_id97004">
        <Image className="bg" src={phoneBg} />

        <View className="title">
          {isLogin ? <View className="title-sub">欢迎使用</View> : '更换手机号'}
          {isLogin ? '人职初' : ''}
        </View>

        <View className="phone-input">
          <View className="input-front">+86</View>
          <View className="line" />
          <Input
            placeholder="请输入手机号码"
            className="inputls"
            value={phone}
            onInput={this.onMobileInput}
            maxLength={11}
            type="number"
          />
        </View>

        {!isSendCode && (
          <Button className={`btn ${cant ? 'btn-opacity' : ''}`} onClick={this.sendMessage}>
            <View className="btn-self">获取验证码</View>
          </Button>
        )}

        {isSendCode && (
          <View className="code-input">
            <Input
              placeholder="短信验证码"
              className="inputls"
              value={validation}
              // maxLength={4}
              onInput={this.onPhoneInput}
              type="number"
            />
            <View
              className={`code-end ${textOpacity ? 'btn-opacity' : ''}`}
              onClick={this.sendMessage}
            >
              {text}
            </View>
          </View>
        )}

        <View className="btn-container">
          <View className="img-btn" onClick={this.onTap}>
            <Image src={checkPhoneMark} />
          </View>
        </View>

        {isLogin && (
          <View className="fixed-rule">
            <View className="rule-text">
              我已阅读并同意
              <Text className="text-bold" onClick={this.goRules}>《人职初条款》</Text>
            </View>
            <View className={`check-btn ${agreeChecked ? 'checked' : ''}`} onClick={this.ruleChecked}>
              <Image src={checkPhoneMark} />
            </View>
          </View>
        )}
      </View>
    )
  }
}

export default PhoneValidation
